//
//  PhotoAlbumListViewController.swift
//  SwiftChatUI
//
//  Created by xzk on 2019/2/26.
//  Copyright © 2019年 xzk. All rights reserved.
//

import UIKit

class PhotoAlbumListViewController: UIViewController {
    
    private var manager: PhotoManager = PhotoManager.shared
    
    private var dataArray: [AlbumModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalTo(self.view)
        }
        
        loadData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: PhotoShouldReloadPhotosNotification, object: nil)
    }
    
    @objc func loadData() {
        manager.albums { (albums) in
            self.dataArray = albums
            self.tableView.reloadData()
        }
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        
        return tableView
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension PhotoAlbumListViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cellID")
        }
        
        let model: AlbumModel = dataArray[indexPath.row]
        cell?.accessoryType = .disclosureIndicator
        cell?.imageView?.image = model.firstImage
        cell?.textLabel?.text = model.albumNamge
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let pictureListVC = PhotoPictureListViewController()
        pictureListVC.album = dataArray[indexPath.row]
            
        navigationController?.pushViewController(pictureListVC, animated: true)
    }
}
